﻿using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Events;

public class AudioEffect : MonoBehaviour
{
    public AudioSource audioSource;
    public UnityAction<AudioEffect> callback;
    public bool isUsing;
    public int order;
    public bool isFade;
    public float volume;
    private bool started;

    // Update is called once per frame
    void Update()
    {
        if (audioSource != null && started && !audioSource.isPlaying)
        {
            callback?.Invoke(this);
            isUsing = false;
            started = false;
        }
    }

    public void Play(AudioClip clip, UnityAction<AudioEffect> callback, int order = 1, bool isFade = true,
        float volume = 1,
        bool isLoop = false,
        bool is3D = false)
    {
        if (clip != null)
        {
            audioSource.clip = clip;
            audioSource.volume = volume;
            audioSource.loop = isLoop;
            audioSource.spatialBlend = is3D ? 1 : 0;
            gameObject.SetActive(true);
            audioSource.Play();
            started = true;
            isUsing = true;
            this.callback = callback;
            this.order = order;
            this.isFade = isFade;
            this.volume = volume;
            name = clip.name;

            // for (int i = 0; i < SoundManager.instance.audioEffects.Count; i++)
            // {
            //     if (SoundManager.instance.audioEffects[i].isUsing && SoundManager.instance.audioEffects[i].isFade &&
            //         SoundManager.instance.audioEffects[i].order > order)
            //     {
            //         DOTween.To(() => SoundManager.instance.audioEffects[i].audioSource.volume,
            //             x => SoundManager.instance.audioEffects[i].audioSource.volume = x,
            //             SoundManager.instance.fadePercent, SoundManager.instance.fadeDuration);
            //     }
            // }
        }
    }

    public void Stop()
    {
        audioSource.Stop();
        isUsing = false;
    }

    public void SetVolume(float volume, float duration)
    {
        DOTween.To(() => audioSource.volume, (x) => audioSource.volume = x, volume, duration);
    }

    public void SetVolume(float volume)
    {
        audioSource.volume = volume;
    }

    public static AudioEffect Create()
    {
        GameObject audioGo = new GameObject("audioGoNew");
        AudioEffect audioEffect = audioGo.AddComponent<AudioEffect>();
        audioGo.gameObject.SetActive(false);
        audioEffect.audioSource = audioGo.AddComponent<AudioSource>();
        audioEffect.audioSource.playOnAwake = false;
        return audioEffect;
    }
}